import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import store from '@/store';
import layout from '@/layouts/index.vue';
import login from 'view/users/login.vue';

const routes: Array<RouteRecordRaw> = [
  {
    name: 'layout',
    path: '/',
    component: layout,
    redirect: '/home',
    children: [{
      name: 'home',
      path: '/home',
      component: () => import('view/index.vue')
    },
    {
      name: 'roles',
      path: '/roles',
      component: () => import('view/roles.vue')
    },
    {
      name: 'users',
      path: '/users',
      component: () => import('view/users/index.vue')
    },
    {
      name: 'userAddress',
      path: '/users/address/:id',
      props: true,
      component: () => import('view/users/address.vue')
    },
    {
      name: 'classify',
      path: '/classify',
      component: () => import('view/classify.vue')
    },
    {
      name: 'goods',
      path: '/goods',
      component: () => import('view/goods.vue')
    },
    {
      name: 'picture',
      path: '/picture',
      component: () => import('view/picture.vue')
    }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/:name(.*)',
    name: 'notFound',
    component: () => import('view/notFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

router.beforeEach((to, from, next) => {
  const { name } = to;
  const token = store.getters.token;
  if (name === 'login' && token) {
    return next({ name: 'home' });
  }
  if (name !== 'login' && !token) {
    return next({ name: 'login' });
  }
  next();
});

export default router
